import 'package:flutter/material.dart';
import 'package:ichinesereader/models/evaluation/evaluationClassReportResult.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';

// ignore: must_be_immutable
class EvaluationClassReportDataGrid extends StatelessWidget {
  EvaluationClassReportDataGrid(
      this.studentEvaluationDetailItems, this.isTeacher);

  List<EvaluationBookReport> studentEvaluationDetailItems;
  bool isTeacher = false;

  bool isWebOrDesktop =
      GetPlatform.isMacOS || GetPlatform.isWeb || GetPlatform.isDesktop;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  DataGridController _dataGridController = DataGridController();

  @override
  Widget build(BuildContext context) {
    Log.debug('build evaluation class report data grid');
    return Column(children: [
      //  Row(
      //         children: [
      //           Text(''),
      //           Expanded(
      //             child: FormBuilderChoiceChip(
      //               labelStyle: TextStyle(
      //                 color: Theme.of(context).primaryColorLight,
      //                 fontSize: 15,
      //                 letterSpacing: 0.8,
      //               ),
      //               backgroundColor: AppTheme.colors.disableBtnLight,
      //               selectedColor: Theme.of(context).primaryColor,
      //               name: 'evaluation_type_chip',
      //               onChanged: (value) {
      //                 if (value != null) {
      //                   var eType = value as AssessmentBookType;
      //                 } else {
      //                   Log.debug('no type selected');
      //                 }
      //               },
      //               initialValue: Constants.evaluationTypes[0],
      //               options: Constants.evaluationTypes
      //                   .map((state) =>
      //                       FormBuilderChipOption<AssessmentBookType>(
      //                         value: state,
      //                         child: Text(
      //                           state.displayName.toString(),
      //                         ),
      //                       ))
      //                   .toList(),
      //             ),
      //           ),
      //         ],
      //       ),
      Expanded(child: _buildDataGrid()),
    ]);
  }

  SfDataGrid _buildDataGrid() {
    return SfDataGrid(
      source:
          StudentEvaluationDataGridSource(items: studentEvaluationDetailItems),
      onQueryRowHeight: (row) {
        return row.rowIndex == 0 ? 50.0 : 49.0;
      },
      //设置表头高度
      controller: _dataGridController,
      showCheckboxColumn: false,
      checkboxColumnSettings: Get.isDarkMode
          ? DataGridCheckboxColumnSettings(
              backgroundColor: Color(0xff0a0e21),
            )
          : DataGridCheckboxColumnSettings(backgroundColor: Colors.blue[50]),
      allowSorting: true,
      allowTriStateSorting: true,
      allowSwiping: false,
      selectionMode: SelectionMode.single,
      navigationMode: GridNavigationMode.row,
      columns: <GridColumn>[
        GridColumn(
          width: isWebOrDesktop ? 160 : 160,
          columnName: 'FirstName',
          label: buildDataGridColumnLabel('FirstName'),
        ),
        GridColumn(
          width: isWebOrDesktop ? 160 : 160,
          columnName: 'LastName',
          label: buildDataGridColumnLabel('LastName'),
        ),
        GridColumn(
          columnName: 'UserName',
          width: 160,
          label: buildDataGridColumnLabel('UserName'),
        ),
        GridColumn(
          columnName: 'Listening',
          width: isWebOrDesktop ? 150 : 150,
          label: buildDataGridColumnLabel('Listening'),
        ),
        GridColumn(
          width: isWebOrDesktop ? 150 : 150,
          columnName: 'Reading',
          visible: isTeacher ? true : false,
          label: buildDataGridColumnLabel('Reading'),
        ),
        GridColumn(
          columnName: 'Speaking',
          width: isWebOrDesktop ? 150.0 : 150.0,
          label: buildDataGridColumnLabel('Speaking'),
        ),
        GridColumn(
          columnName: 'Writing',
          width: isWebOrDesktop ? 150 : 150,
          label: buildDataGridColumnLabel('Writing'),
        ),
        GridColumn(
          columnName: 'AI Speaking',
          width: isWebOrDesktop ? 150.0 : 150.0,
          label: buildDataGridColumnLabel('AI Speaking'),
        ),
      ],
    );
  }
}

class StudentEvaluationDataGridSource extends DataGridSource {
  StudentEvaluationDataGridSource({required List<EvaluationBookReport> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'FirName', value: dataGridRow.firstName),
              DataGridCell<String>(
                  columnName: 'LastName', value: dataGridRow.lastName),
              DataGridCell<String>(
                  columnName: 'UserName', value: dataGridRow.userName),
              DataGridCell<String>(
                  columnName: 'Listening',
                  value: dataGridRow.listeningAccuracy.toString()),
              DataGridCell<String>(
                  columnName: 'Reading',
                  value: dataGridRow.readingAccuracy.toString()),
              DataGridCell<String>(
                  columnName: 'Speaking',
                  value: dataGridRow.speakingScore.toString()),
              DataGridCell<String>(
                  columnName: 'Writing',
                  value: dataGridRow.writingScore.toString()),
              DataGridCell<String>(
                  columnName: 'AI Speaking',
                  value: dataGridRow.speakingAiScore.toString()),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'UserName') {
            if (GetPlatform.isMacOS || GetPlatform.isWeb) {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: GestureDetector(
                    onTap: () {},
                    child: Text(
                      dataGridCell.value,
                      style: Get.textTheme.titleLarge,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ));
            } else {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: GestureDetector(
                    onTap: () {
                      // var type = row
                      //     .getCells()
                      //     .where((element) => element.columnName == 'Type')
                      //     .first
                      //     .value;
                      // var username = row
                      //     .getCells()
                      //     .where((element) => element.columnName == 'Username')
                      //     .first
                      //     .value;
                      // var questionId = row
                      //     .getCells()
                      //     .where((element) => element.columnName == 'Id')
                      //     .first
                      //     .value;
                      // if (isTeacher) {
                      //   Get.to(() => InAppWebViewTeacherQuzibookReviewScreen(
                      //       type: type,
                      //       username: username,
                      //       questionId: questionId));
                      // } else {
                      //   Get.to(() => InAppWebViewStudentQuizbookReviewScreen(
                      //       type: type,
                      //       username: username,
                      //       questionId: questionId));
                      // }
                    },
                    child: Text(
                      dataGridCell.value,
                      style: TextStyle(
                          color: Colors.blue[300], fontWeight: FontWeight.bold),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ));
            }
          } else if (dataGridCell.columnName == 'Reading' ||
              dataGridCell.columnName == 'Listening') {
            var points = double.tryParse(dataGridCell.value.toString()) ?? 0;
            String numberStr = (points / 10).toStringAsFixed(1);

            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  numberStr.replaceAll('0.0', '0'),
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          } else if (dataGridCell.columnName == 'AI Speaking') {
            var points = double.tryParse(dataGridCell.value.toString()) ?? 0;
            String numberStr = (points / 10).toStringAsFixed(1);

            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  numberStr.replaceAll('0.0', '0'),
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  dataGridCell.value.toString(),
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
